//
//  WmcBrowseImagePerview.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/30.
//

import UIKit
import YPBedrock

// MARK: - [WmcImageBrowsePreview]

class WmcImageBrowsePreview: WmcBaseView {
    /// 缓存表
    static var ImageCacheMap: [String: UIImage] = [:]

    lazy var scrollView: UIScrollView = {
        scrollView = UIScrollView()
        scrollView.maximumZoomScale = defaultMaxZoomScale
        scrollView.minimumZoomScale = 1
        scrollView.isMultipleTouchEnabled = true
        scrollView.delegate = self
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.delaysContentTouches = false
        return scrollView
    }()

    lazy var containerView: UIView = {
        let view = UIView()
        return view
    }()

    lazy var imageView: UIImageView = {
        imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()

    lazy var progressView: WmcLoadImageProgressView = {
        let view = WmcLoadImageProgressView()
        return view
    }()

    /// 默认最大缩放
    let defaultMaxZoomScale: CGFloat = 3
    /// 单击回调
    var singleTapBlock: (() -> Void)?
    /// 双击回调
    var doubleTapBlock: (() -> Void)?

    var onFetchingGif = false

    var fetchGifDone = false

    /// 浏览的图片
    var image: UIImage? { self.imageView.image }

    /// 清空缓存表
    static func ClearImageCacheMap() {
        ImageCacheMap = [:]
    }

    func configImage(_ wmc_image: WmcImage?) {
        imageView.image = nil
        guard let wmc_image = wmc_image else { return }
        scrollView.zoomScale = 1
        let hashKey = wmc_image.hashKey
        if let uiImage = Self.ImageCacheMap[hashKey] {
            imageView.image = uiImage
            layoutSubviews()
        } else {
            switch wmc_image.imageType {
            case .url(let url):
                let _url = URL.YP.Create(url)
                imageView.kf.setImage(with: _url,
                                      placeholder: "image_placeholder".wmc_image,
                                      options: [.transition(.fade(0.3))]) { [weak self] receivedSize, totalSize in
                    guard let weakSelf = self else { return }
                    let progress = CGFloat(receivedSize) / CGFloat(totalSize)
                    weakSelf.progressView.progress = progress
                    weakSelf.progressView.isHidden = progress >= 1
                } completionHandler: { [weak self] result in
                    guard let weakSelf = self else { return }
                    weakSelf.progressView.isHidden = true
                    weakSelf.layoutSubviews()
                }
            default:
                wmc_image.loadUIImage { [weak self] image in
                    guard let weakSelf = self else { return }
                    Self.ImageCacheMap[hashKey] = image
                    weakSelf.imageView.image = image
                    weakSelf.layoutSubviews()
                }
            }
        }
    }
    /// 需要另外触发的视图
    var hitTestViews: [UIView] = []
    /// 重置大小后回调
    var resetSubViewSizeBlock: YPBlock.OneParam<CGSize>?
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let supView = super.hitTest(point, with: event)
        
        for view in hitTestViews {
            let frame = view.convert(view.bounds, to: self)
            if frame.contains(point) {
                return view
            }
        }
        return supView
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        scrollView.frame = bounds
        scrollView.zoomScale = 1
        resetSubViewSize()
    }

    override func makeUI() {
        backgroundColor = .black

        addSubview(scrollView)
        scrollView.addSubview(containerView)
        containerView.addSubview(imageView)
        addSubview(progressView)
        progressView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        // 单击
        let singleTap = UITapGestureRecognizer.YP.Create { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.singleTapBlock?()
        }
        addGestureRecognizer(singleTap)
        // 双击
        let doubleTap = UITapGestureRecognizer.YP.Create { [weak self] tap in
            guard let weakSelf = self else { return }
            weakSelf.doubleTapAction(tap)
        }
        doubleTap.numberOfTapsRequired = 2
        addGestureRecognizer(doubleTap)

        singleTap.require(toFail: doubleTap)
    }

    func doubleTapAction(_ tap: UITapGestureRecognizer) {
        let scale: CGFloat = scrollView.zoomScale != scrollView.maximumZoomScale ? scrollView.maximumZoomScale : 1
        let tapPoint = tap.location(in: self)
        var rect = CGRect.zero
        rect.size.width = scrollView.frame.width / scale
        rect.size.height = scrollView.frame.height / scale
        rect.origin.x = tapPoint.x - (rect.size.width / 2)
        rect.origin.y = tapPoint.y - (rect.size.height / 2)
        self.scrollView.zoom(to: rect, animated: true)
    }

    func resetSubViewSize() {
        guard let size = imageView.image?.size else { return }
        var frame: CGRect = .zero
        let viewW = bounds.width
        let viewH = bounds.height
        let width = viewW
//        if UIApplication.shared.statusBarOrientation.isLandscape { // 横屏
//            let height = viewH
//            frame.size.height = height
//            let imageWHRatio = size.width / size.height
//            let viewWHRatio = viewW / viewH
//            if imageWHRatio > viewWHRatio {
//                frame.size.width = floor(height * imageWHRatio)
//                if frame.size.width > viewW { // 宽图
//                    frame.size.width = viewW
//                    frame.size.height = viewW / imageWHRatio
//                }
//            } else {
//                width = floor(height * imageWHRatio)
//                if width < 1 || width.isNaN {
//                    width = viewW
//                }
//                frame.size.width = width
//            }
//        } else {
        // 竖屏
        frame.size.width = width
        let imageHWRatio = size.height / size.width
        var height: CGFloat = viewH
        if size.height > size.width { // 长竖图
            height = floor(frame.size.width * imageHWRatio)
            if height > viewH { // 比例计算后的高大于视图高，则继续缩放
                let hRatio = viewH / height
                height = viewH
                frame.size.width = width * hRatio
            }
        } else if size.height < size.width { // 宽横图
            height = floor(frame.size.width * imageHWRatio)
        } else { // 正方图
            height = width
        }
        if height < 1 || height.isNaN {
            height = viewH
        }
        frame.size.height = height
//        }

        // 优化 scroll view zoom scale
        if frame.width < frame.height {
            scrollView.maximumZoomScale = max(defaultMaxZoomScale, viewW / frame.width)
        } else {
            scrollView.maximumZoomScale = max(defaultMaxZoomScale, viewH / frame.height)
        }
        containerView.frame = frame

        var contenSize: CGSize = .zero
        if UIApplication.shared.statusBarOrientation.isLandscape {
            contenSize = CGSize(width: width, height: max(viewH, frame.height))
            if frame.height < viewH {
                containerView.center = CGPoint(x: viewW / 2, y: viewH / 2)
            } else {
                containerView.frame = CGRect(origin: CGPoint(x: (viewW - frame.width) / 2, y: 0), size: frame.size)
            }
        } else {
            contenSize = frame.size
            if frame.height < viewH {
                containerView.center = CGPoint(x: viewW / 2, y: viewH / 2)
            } else {
                containerView.frame = CGRect(origin: CGPoint(x: (viewW - frame.width) / 2, y: 0), size: frame.size)
            }
        }

//        YPGCD.Delay(delay: 0.3) { [weak self] in
//            guard let weakSelf = self else { return }
        scrollView.contentSize = contenSize
        imageView.frame = containerView.bounds
        scrollView.contentOffset = .zero
//        }
        
        resetSubViewSizeBlock?(containerView.frame.size)
    }
}

// MARK: - UIScrollViewDelegate

extension WmcImageBrowsePreview: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.containerView
    }

    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        let offsetX = (scrollView.frame.width > scrollView.contentSize.width) ? (scrollView.frame.width - scrollView.contentSize.width) * 0.5 : 0
        let offsetY = (scrollView.frame.height > scrollView.contentSize.height) ? (scrollView.frame.height - scrollView.contentSize.height) * 0.5 : 0
        self.containerView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//        self.resumeGif()
    }
}
